<template>
  <text>{{ date }}</text>
</template>

<script lang="ts" setup>
  import { useIntervalFn } from '@vueuse/core';
  import { ref, watch } from 'vue';

  import {
    formatToDate,
    formatToDateTime,
    getRelativeTime,
    getTimeStamp,
    ONE_SECONDS,
  } from '@/utils/date';
  import { propTypes } from '@/utils/propTypes';

  defineOptions({
    name: 'ea-time',
    options: {
      virtualHost: true,
      addGlobalClass: true,
      styleIsolation: 'shared',
    },
  });
  const props = defineProps({
    value: {
      type: Object as PropType<number | Date | string>,
      required: true,
    },
    step: propTypes.number(60),
    mode: {
      type: String as PropType<'date' | 'datetime' | 'relative'>,
      default: 'relative',
    },
  });

  const date = ref('');

  function setTime() {
    const { mode, value } = props;
    const time = getTimeStamp();
    if (mode === 'relative') {
      date.value = getRelativeTime(time);
    } else {
      if (mode === 'datetime') {
        date.value = formatToDateTime(value);
      } else if (mode === 'date') {
        date.value = formatToDate(value);
      }
    }
  }

  useIntervalFn(setTime, props.step * ONE_SECONDS);

  watch(
    () => props.value,
    () => {
      setTime();
    },
    { immediate: true },
  );
</script>

<style lang="scss" scoped></style>
